<?php


namespace App\Models\CacheModel\active;


use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

class Active1CouponRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.active1_coupon_record';

    protected $cacheModel = 'active.give_coupon';

    /**
     * 写入 优惠券
     * @param array $data
     */
    public function SaveData(array $data)
    {
        try
        {
            // $data = [
            //     'active_flag' => 111,
            //     'uid' => 111,
            //     'type' => 111,
            //     'flag' => 111,
            //     'cid' => 111,
            //     'create_time' => 111,
            // ];
            $this->save($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $data['active_flag'] . ':' . $data['uid'] . ':' . $data['type'])->setCache([$data['flag'] => $data['cid']]);
        }
        catch (\Exception $e)
        {
            Log::write('Active1CouponRecord model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
        }
    }

    /**
     * 获取已领取优惠券 数据
     * @param int $activeFlag 活动标识
     * @param int $uid 用户uid
     * @param int $type 类型 1=>签到领券  2=>助力领券
     * @return array
     * @throws \Exception
     */
    public function getCouponData(int $activeFlag, int $uid, int $type): array
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $activeFlag . ':' . $uid . ':' . $type)->getDataAndSet(function () use ($activeFlag, $uid, $type)
        {
            try
            {
                $data = $this->where(['active_flag' => $activeFlag, 'uid' => $uid, 'type' => $type])->column('cid', 'flag');

                $da = [0 => 0];
                foreach ($data as $key => $cid)
                {
                    $da[$key] = $cid;
                }

                return $da;
            }
            catch (\Exception $e)
            {
                Log::write('Active1CouponRecord model => getCouponData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');

                return [];
            }
        });

        unset($data[0]);

        return $data;
    }
}
